<template>
  <div class="container">
    <div class="login-content">
      <img :src="logoUrl">
    </div>
    <div class="sign-list">
      <ul class="login-list">
        <li>
          <i class="fa fa-user"></i>
          <input type="text"
                 placeholder="请输入用户名"
                 v-model="loginData.phone" />
        </li>
        <li>
          <i class="fa fa-lock"></i>
          <input type="password"
                 placeholder="请输入密码"
                 v-model="loginData.password" />
        </li>
        <a href="javascript:void(0)"
           @click="toForgetPassword"
           style="color:#666;float: right;text-decoration: underline;">忘记密码</a>
      </ul>
      <mt-button size="large"
                 type="danger"
                 @click.native="handleClick">登录</mt-button>
    </div>
  </div>
</template>
<script>
import { Toast } from "mint-ui";
export default {
  data() {
    return {
      logoUrl: "",
      loginData: {
        phone: "",
        password: "",
        wxOpenId: window.localStorage.getItem("2_wxOpenid")
      }
    };
  },
  mounted: function () {
    //if(!window.localStorage.getItem("2_wxOpenid")) {
    var phone = window.localStorage.getItem("2_phone");
    var password = window.localStorage.getItem("2_password");
    // alert("login:phone->" + phone + ", password->" + password);
    if (!this.getQueryString("companyUuid")) {
      this.getCompanyLogo();
      this.autoLogin();
    } else if (this.getQueryString("openId")) {
      window.localStorage.setItem("2_wxOpenid", this.getQueryString("openId"));
      this.getCompanyLogo();
      this.autoLogin();
    } else {
      this.wxAuth();
    }
    window.localStorage.setItem(
      "2_companyUuid",
      this.getQueryString("companyUuid")
    );
    // } else {
    //     this.getCompanyLogo();
    //     this.autoLogin();
    // }
  },
  methods: {
    toForgetPassword() {
      var _self = this;
      this.$router.push({
        path: "/forgetPassword"
      });
    },
    getCompanyLogo() {
      var _self = this;
      var body = {};
      body.params = { logoType: "2" };
      var url = _self.utilHelper.apiUrl + "/api/getLogo";
      _self.$http.post(url, body).then((response) => {
        var data = response.body.resData;
        if (data.result == "1") {
          _self.logoUrl = data.logoUrl;
        } else {
          _self.logoUrl = require("./assets/images/logoA.png");
        }
      });
    },
    getQueryString(name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
      var r = window.location.search.substr(1).match(reg);
      if (r != null) {
        return unescape(r[2]);
      }
      return null;
    },
    wxAuth() {
      var url = this.utilHelper.apiUrl + "/weixin/getWxConfig";
      this.$http.post(url, null).then((response) => {
        var body = response.body;
        if (body.code == "success") {
          this.gotoWeiXinAuth(body.appId, body.companyUuid);
        } else if (body.code == "fail") {
          //没有配置微信授权路径
          this.getCompanyLogo();
          this.autoLogin();
        } else {
          console.log(body);
        }
      });
    },
    //微信静默授权请求
    gotoWeiXinAuth(appId, companyUuid) {
      let systemId = "2";
      var state =
        companyUuid +
        "|" +
        window.location.hostname +
        "|" +
        encodeURIComponent(window.location.pathname) +
        "|login|" +
        systemId;
      let redirect_uri = this.utilHelper.apiUrl + "/weixin/getWeiXinAuth";
      if (this.$route.query.redirectUrl) {
        redirect_uri += "?bus_uri=" + this.$route.query.redirectUrl;
      }
      var weixinUrl =
        "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
        appId +
        "&redirect_uri=" +
        encodeURIComponent(redirect_uri) +
        "&response_type=code&scope=snsapi_base&state=" +
        state +
        "&connect_redirect=1#wechat_redirect";
      window.location.href = weixinUrl;
    },
    handleClick() {
      var _self = this;
      if (_self.vaild()) {
        _self.loginData.domain = window.location.href;
        _self.loginData.wxOpenId =
          window.localStorage.getItem("2_wxOpenid") ||
          this.getQueryString("openId");
        var body = {};
        body.params = _self.loginData;
        var pwd = _self.loginData.password;
        var url = _self.utilHelper.apiUrl + "/api/login";
        _self.$http.post(url, body).then(
          (response) => {
            var data = response.body.resData;
            var result = data.result;
            var errorMsg = data.resultMsg;
            if (result == "1") {
              window.localStorage.setItem("2_userId", data.id);
              window.localStorage.setItem("2_userName", data.accountName);
              window.localStorage.setItem(
                "2_password",
                _self.loginData.password
              );
              window.localStorage.setItem("2_phone", data.phone);
              //登录的时候传递所有的能查看的楼盘ID
              // window.localStorage.setItem("2_premisesId", "2471");
              //  window.localStorage.setItem("2_premisesName", "友谊二村");
              if (data.premisesIds) {
                window.localStorage.setItem("2_premisesIds", data.premisesIds);
              } else {
                window.localStorage.setItem("2_premisesIds", [-1]);
              }

              window.localStorage.setItem("2_premisesName", "已选择全部楼盘");
              window.localStorage.setItem("2_isLogin", true);

              if (_self.$route.query.redirectUrl) {
                _self.$router.replace({
                  path: _self.$route.query.redirectUrl
                });
              } else {
                _self.$router.replace({
                  path: "/indexNav"
                });
              }
            } else if (response.body.result == "1000") {
              layer.msg(data.errorMsg, {
                time: 1000
              });
            } else {
              if (errorMsg) {
                Toast({
                  message: errorMsg,
                  position: "middle",
                  duration: 3000
                });
              }
            }
          },
          (response) => {
            Toast({
              message: "登陆超时",
              position: "middle",
              duration: 3000
            });
          }
        );
      }
    },
    vaild() {
      var _self = this;
      if (!_self.loginData.phone) {
        Toast({
          message: "请输入用户名",
          position: "middle",
          duration: 3000
        });
        return false;
      }
      if (!_self.loginData.password) {
        Toast({
          message: "请输入密码",
          position: "middle",
          duration: 3000
        });
        return false;
      }
      return true;
    },
    autoLogin() {
      var _self = this;
      var phone = window.localStorage.getItem("2_phone");
      var password = window.localStorage.getItem("2_password");
      var wxOpenId =
        window.localStorage.getItem("2_wxOpenid") ||
        this.getQueryString("openId");
      var loginData = {};
      loginData.phone = phone;
      if (!password) {
        return;
      } else {
        loginData.password = password;
      }

      loginData.domain = window.location.href;
      loginData.wxOpenId = wxOpenId;
      loginData.cooCompanyId = "";
      if (phone) {
        var body = {};
        body.params = loginData;
        var url = _self.utilHelper.apiUrl + "/api/login";
        _self.$http.post(url, body).then(
          (response) => {
            var data = response.body.resData;
            var result = data.result;
            var errorMsg = data.resultMsg;
            if (result == "1") {
              window.localStorage.setItem("2_userId", data.id);
              window.localStorage.setItem("2_userName", data.accountName);
              window.localStorage.setItem(
                "2_password",
                _self.loginData.password
              );
              window.localStorage.setItem("2_phone", data.phone);
              window.localStorage.setItem("2_isLogin", true);
              window.localStorage.setItem("2_userRole", data.userRoleId);
              window.localStorage.setItem("2_accountType", data.accountType);
              if (_self.$route.query.redirectUrl) {
                _self.$router.replace({
                  path: _self.$route.query.redirectUrl
                });
              } else {
                _self.$router.replace({
                  path: "/indexNav"
                });
              }
            } else {
              layer.msg(errorMsg, {
                time: 1000
              });
            }
          },
          (response) => {
            // layer.msg('登陆超时', {
            //     time: 1000
            // });
          }
        );
      }
    }
  }
};
</script>
<style scoped>
.login-content img {
  height: 260px;
  width: 100%;
}
.login-list {
  margin: 50px 0;
}
.sign-list {
  padding: 0 22px;
}
.login-list li {
  border-bottom: 1px solid #cdcdcd;
  line-height: 48px;
  height: 48px;
  padding-left: 50px;
  position: relative;
  margin-bottom: 10px;
  padding-right: 20px;
}
.login-list > li .fa {
  position: absolute;
  left: 12px;
  top: 14px;
  font-size: 20px;
  color: #cdcdcd;
}
.login-list > li input {
  height: 24px;
  line-height: 24px;
  width: 100%;
  background-color: #f8f5f3;
}
.mint-button--danger {
  background-color: #eb6100;
}
</style>